<!-- // 客户中心 客户列表页面 -->
<template>
    <article class="container">
        <ZwSearchForm row-num="3" :option="searchOption" @search="search" @reset="reset" />
        <div class="customer-manage-list layout">
            <div class="btns">
                <span class="lable-name">看板内容</span>
                <el-button v-auth="'STATISTICS'" type="primary" @click="getStatistics">统计</el-button>
            </div>
            <div class="box-contant">
                <div v-for="(item, index) in datasouch" :key="index" class="boxs">
                    <div class="title">{{ item.stage_name }}（{{ item.num }}）</div>
                    <el-scrollbar height="500px">
                        <div>
                            <div v-for="(itemlist, indexlist) in item.list" :key="indexlist" class="listcontant">
                                <div class="contant" @click="toDetail(itemlist)">
                                    <div class="imgsbtn">
                                        <el-image :src="itemlist.avatar || defaultAvatar" fit="cover" class="titleimg">
                                            <template #error>
                                                <div class="image-slot">
                                                    <el-icon><icon-picture /></el-icon>
                                                </div>
                                            </template>
                                        </el-image>
                                        <span>
                                            <div class="name">{{ itemlist.name }}</div>
                                            <div style="display: flex">
                                                <div
                                                    v-for="(itemlistkey, indexlistkey) in itemlist.source"
                                                    :key="indexlistkey"
                                                    class="imgs-ionic">
                                                    <img
                                                        v-if="itemlistkey == 0"
                                                        class="img-ionic"
                                                        src="@/assets/image/customer/douyin.png"
                                                        alt="" />
                                                    <img
                                                        v-if="itemlistkey == 1"
                                                        class="img-ionic"
                                                        src="@/assets/image/customer/wchat.png"
                                                        alt="" />
                                                    <img
                                                        v-if="itemlistkey == 2"
                                                        class="img-ionic"
                                                        src="@/assets/image/customer/qiyewchat.png"
                                                        alt="" />
                                                </div>
                                            </div>
                                        </span>
                                    </div>
                                    <div class="enterprise">
                                        <span>企业：</span>
                                        <span class="enterpriseno">{{ itemlist.company_name }}</span>
                                    </div>
                                    <div class="enterprise communicate">
                                        <span>{{ itemlist.communicate_day }}天前沟通</span>
                                        <span class="enterpriseno">{{ itemlist.employee_name }}</span>
                                    </div>
                                </div>
                            </div>
                            <!-- <el-empty v-if="item.num == 0" description="暂无客户" image-size="50"></el-empty> -->
                            <div
                                v-if="item.num == 0"
                                style="width: 100%; display: flex; justify-content: center; align-items: center">
                                <el-empty description="暂无客户"></el-empty>
                            </div>
                        </div>
                    </el-scrollbar>
                </div>
                <!-- <el-empty v-if="datasouch.length == 0" description="暂无客户" image-size="150"></el-empty> -->
                <div
                    v-if="datasouch.length == 0"
                    style="width: 100%; display: flex; justify-content: center; align-items: center">
                    <el-empty description="暂无客户"></el-empty>
                </div>
            </div>

            <!-- 部门人员弹框 -->
            <ZWDepart ref="DepartRef" @submit="getZWDepartData" />
            <!-- 添加客户 -->
            <AddCustomer ref="AddCustomerRef" :source-arr="sourceArr" @save="getListFun" />
            <!-- 导入客户的弹框 -->
            <ImportCustomer ref="ImportCustomerRef" @save="getListFun" />

            <!-- 批量标签弹框 -->
            <BatchLabel ref="BatchLabelRef" @save="getTagsFun" />
            <!-- 群聊 -->
            <GroupChart ref="GroupChartRef" @submit="getGroupFun" />
        </div>
    </article>
</template>

<script lang="tsx">
import { defineComponent } from 'vue';
// 定义name专用script标签
// eslint-disable-next-line vue/component-definition-name-casing
export default defineComponent({ name: 'CUSTOMER_MANAGE_BULLETIN' });
</script>

<script setup lang="tsx">
import ZwSearchForm from '@/components/zw/search-form/SearchForm';
import ZWDepart from '@/components/ZWDepart.vue';
import ZWPagination from '@/components/ZWPagination.vue';
import AddCustomer from './components/AddCustomer.vue';
import ImportCustomer from './components/ImportCustomer.vue';
import BatchLabel from '@/components/BatchLabel.vue';
import GroupChart from '@/components/chart/GroupChart.vue';
import { Search, Picture as IconPicture, ArrowDownBold, ArrowUpBold } from '@element-plus/icons-vue';
import { exportCustomer, batchAssignStaff, batchAddTag, batchRmTag } from '@/api/customerCenter';
import { getSyncTime, custSync, custSyncResult, getCustormerList } from '@/api/customerCenter/groupManage';
import { sourceList } from '../configure/api';
import { getBoard } from '@/api/customerbulletin/bulleinManage';
import { useStore } from '@/store';
import { ref, reactive, watch, computed, onActivated } from 'vue';
import { IsNotEmpty, getSetionId, AFold } from '@/utils/utils';
import { deepCopy } from '@/utils/helper';
import router from '@/router';
import { ElMessage, ElLoading, ElForm } from 'element-plus';
import cityData from '@/assets/js/city';
import { time } from 'echarts';
const tabsList = ref([]); //当前选中的标签的展示数组
const store = useStore();
const DepartRef = ref({});
// const formRef = ref({})
const formRef = ref<InstanceType<typeof ElForm>>();
const ImportCustomerRef = ref({});
const AddCustomerRef = ref({});
const BatchLabelRef = ref({});
const showDepart = ref(true);
const users = ref([]);
const groupchats = ref([]);
const GroupChartRef = ref({});
const updateTime = ref('');
const chooseTableData = ref([]); //当前选中的表格的数据
const departTypeObj = {
    departType: '', //当前打卡选择员工的类型
    departData: [], //选中的数据
    itemData: '' //当前传入的数据
};
// const departTypeObj = reactive({
//   departType: '', //当前打卡选择员工的类型
//   departData: [], //选中的数据
//   itemData: '' //当前传入的数据
// })

const requestFlag = ref<boolean>(false);
const currentParams = ref<any>(null);

const defaultAvatar = ref('https://img-scrm-dev.keyid.cn/keyid-scrm-server/avatar/cust_default.png');

const defaultParams = {
    tags: [], //选择的标签
    create_time: [], //添加时间
    employee_ids: [], //员工id
    mobileornickname: '', //客户手机号/姓名搜索
    is_wx_work: -1, //是否企微，-1: 全部， 0：非企微， 1：企微
    source_id: -1, //全部 -1
    touch_mode: -1, //可触达方式
    location: [], //所在地
    status: -1, //客户状态  -1 全部  0已流失 1正常  2异常
    stage: -1, //客户阶段 -1全部
    groupchat_id: 0, //群聊 -1全部
    is_protect: -1, //客户保护 -1全部 1-已保护 2-未保护
    select_tag_type: -1
};
const state = reactive({
    searchParams: deepCopy(defaultParams)
});
const formData = reactive({});
const searchOption = computed(() => {
    return [
        {
            label: '是否企微',
            name: 'is_wx_work',
            value: '-1',
            type: 'select',
            placeholder: '全部',
            optionList: [
                {
                    label: '全部',
                    value: '-1'
                },
                {
                    label: '企微客户',
                    value: '1'
                },
                {
                    label: '非企微客户',
                    value: '0'
                }
            ]
        },
        {
            label: '选择员工',
            name: 'employee_ids',
            value: [],
            type: 'select',
            placeholder: '全部',
            multiple: true,
            popperClass: 'zw-hide_select_option',
            isUserSelect: true,
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '客户手机号/昵称',
            name: 'mobileornickname',
            value: '',
            type: 'input',
            placeholder: '请输入客户手机号/昵称'
        },
        {
            label: '客户来源',
            name: 'source_id',
            value: [],
            type: 'select',
            placeholder: '请选择客户来源',
            multiple: false,
            collapseTags: true,
            filterable: true,
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    sourceList({ page: 1, page_size: 99999 }).then((r: any) => {
                        r.data = r.data || [];
                        resolve(r.data);
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '可触达方式',
            name: 'touch_mode',
            value: '',
            type: 'select',
            placeholder: '请选择客户可触达方式',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    resolve([
                        { name: '全部', id: '-1' },
                        { name: '短信', id: '0' },
                        { name: '企业微信', id: '1' },
                        { name: '微信', id: '2' },
                        { name: '抖音消息', id: '3' },
                        { name: '公众号', id: '4' },
                        { name: '邮箱', id: '5' }
                    ]);
                });
            },
            formatOption: (v: { name: any; id: any }) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '所在地',
            name: 'location',
            value: '',
            options: cityData,
            props: defaultProps,
            type: 'cascader'
        },
        {
            label: '选择客户标签',
            name: 'tags',
            value: [],
            type: 'select',
            tagTypeName: 'select_tag_type',
            popperClass: 'zw-hide_select_option',
            multiple: true,
            isBatchLabel: true
        },
        {
            label: '客户状态',
            name: 'status',
            value: '-1',
            type: 'select',
            placeholder: '请选择客户客户状态',
            optionList: [
                { label: '全部', value: '-1' },
                { label: '已流失', value: '0' },
                { label: '正常', value: '1' },
                { label: '异常', value: '2' }
            ]
        },
        {
            label: '创建时间',
            name: 'create_time',
            value: [],
            type: 'datePicker',
            datePickerType: 'daterange',
            datePickerFormat: 'YYYY-MM-DD HH:mm:ss',
            valueFormat: 'YYYY-MM-DD HH:mm:ss',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期'
        },
        {
            label: '客户阶段',
            name: 'stage',
            value: '',
            type: 'select',
            placeholder: '请选择客户客户阶段',
            fetchOptionApi: () => {
                return new Promise(resolve => {
                    getCustormerList().then((res: any) => {
                        resolve([{ name: '全部', id: -1 }, ...res]);
                        res;
                    });
                });
            },
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },
        {
            label: '所在群聊',
            name: 'groupchat_id',
            value: '',
            type: 'select',
            placeholder: '全部',
            popperClass: 'zw-hide_select_option',
            isGroupSelect: true,
            multiple: false,
            formatOption: (v: any) => ({
                label: v.name,
                value: v.id
            })
        },

        {
            label: '客户保护',
            name: 'is_protect',
            value: '-1',
            type: 'select',
            placeholder: '请选择客户客户保护',
            optionList: [
                { label: '全部', value: '-1' },
                { label: '已保护', value: '1' },
                { label: '未保护', value: '0' }
            ]
        }
    ];
});
const search = (v: any) => {
    state.searchParams = { ...deepCopy(defaultParams), ...v, stage: v.stage || -1 };
    currentParams.value = { ...deepCopy(defaultParams), ...v, stage: v.stage || -1 };
    getListFun();
};
const reset = (v: any) => {
    state.searchParams = { ...deepCopy(defaultParams) };
    getListFun();
    currentParams.value = { ...deepCopy(defaultParams) };
};
const pageType = reactive({
    type: 0,
    isCheck: false,
    list: [
        { type: 0, name: '当前页' },
        { type: 1, name: '全部页' }
    ]
});

// 创建人options
const creators = ref([]);

const shortcuts = reactive([
    {
        text: '上1周',
        value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            return [start, end];
        }
    },
    {
        text: '上1个月',
        value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            return [start, end];
        }
    },
    {
        text: '前3个月',
        value: () => {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            return [start, end];
        }
    }
]);
const visible = ref(true);
const pickUp = () => {
    visible.value = !visible.value;
    AFold(visible.value, '.el_filter_row');
};
// 来源字典

//所在地
const defaultProps = {
    checkStrictly: true, // 是否严格的遵守父子节点不互相关联
    emitPath: false,
    multiple: true,
    label: 'name',
    value: 'id'
};

const datasouch = ref([]);

const groupOptions = ref([]);
// 获取群聊
const getGroupFun = (val: any) => {
    groupOptions.value = [val];
    state.searchParams.groupchat_id = val.group_id;
};

// 显示群聊
const showGroupBox = () => {
    GroupChartRef.value.appDialog.visible = true;
    GroupChartRef.value.single = true;
};
// let isRequest = false //防止重复点击
const getListFun = () => {
    // debugger
    // if (!isRequest) {
    //   isRequest = true

    getBoard(state.searchParams)
        .then((r: any) => {
            datasouch.value = r;
        })
        .catch((e: any) => {
            // isRequest = false
        });
    // }
};
getListFun();

const getSyncTimeFun = () => {
    getSyncTime({ sync_type: 120 }).then((r: any) => {
        updateTime.value = r.weiwork_synctime;
    });
};
getSyncTimeFun();

//跳转统计
const getStatistics = () => {
    router.push(`/customer/manage/bulletin/detail`);
};

let timeId: any = '';
let loading: any = '';
const checkSuccessSync = (jobid: string) => {
    custSyncResult({ jobid, type: 1 }).then((r: any) => {
        loading = ElLoading.service({
            lock: true,
            text: '同步中....',
            background: 'rgba(0, 0, 0, 0.7)'
        });
        if (!r) {
            loading.close();
            clearInterval(timeId);
            getSyncTimeFun();
            getListFun();
            timeId = '';
            ElMessage.error('同步失败');
            return;
        }
        if (r.status > 1) {
            loading.close();
            clearInterval(timeId);
            getSyncTimeFun();
            getListFun();
            timeId = '';
            ElMessage[r.status == 2 ? 'success' : 'error'](r.status == 2 ? '同步成功' : '同步失败');
        } else {
            if (!timeId) {
                timeId = setInterval(() => {
                    checkSuccessSync(jobid);
                }, 3000);
            }
        }
    });
};

const labelObj = {
    type: '', //当前打开选择标签是哪个类型
    data: [] //选中标签的数据存储
};
//切换标签
const changeLabel = (value: any) => {
    tabsList.value = tabsList.value.filter((item: any) => {
        return item.id == value;
    });
};
// 打开选择标签弹框
const openBatchLabel = (type: string) => {
    labelObj.type = type;
    BatchLabelRef.value.dialogData.labelChooseType = type == 'formData' ? 2 : 1;
    BatchLabelRef.value.chooseDataArr = [];
    if (tabsList.value.length > 0 && type == 'formData') {
        BatchLabelRef.value.chooseDataArr = tabsList.value;
    }
    BatchLabelRef.value.dialogVisible = true;
};
const getTagType = (num: number) => {
    switch (num) {
        case 0:
            return 3;
        case 1:
            return 2;
        case 2:
            return 1;
    }
};
// 获取当前选中的标签
const getTagsFun = (val: any) => {
    if (labelObj.type == 'formData') {
        formData.tags = val.idList;
        //  3: 无标签，2：满足任意一个标签， 1：同时满足所有标签
        // formData.select_tag_type = getTagType(val.labelType)
        formData.select_tag_type = val.labelType;
        tabsList.value = val.data;
        return;
    }
    const param = {
        customer_list: chooseTableData.value.map(it => {
            return it.id;
        }),
        tag_list: val.idList
    };
    //  3批量打标签  4 批量删除标签
    if (val.labelType == 3) {
        batchAddTagFun(param);
        return;
    }
    batchRmTagFun(param);
};
// 批量打标签
const batchAddTagFun = (param: object) => {
    batchAddTag(param).then((r: object) => {
        getListFun();
    });
};
// 批量删除标签
const batchRmTagFun = (param: object) => {
    batchRmTag(param).then((r: object) => {
        getListFun();
    });
};
// let departTypeObj = {
//   departType: '', //当前打卡选择员工的类型
//   departData: [], //选中的数据
//   itemData: '' //当前传入的数据
// }
// 获取当前选中的客户
const handleSelectionChange = (val: any) => {
    chooseTableData.value = val;
};
const openDepart = (type: string, data: any) => {
    departTypeObj.departType = type;
    if (type != 'formData') {
        departTypeObj.departData = [];
    }
    if (data) {
        departTypeObj.itemData = data;
        DepartRef.value.appDialog.chooseArr =
            data.cust_distribution && data.cust_distribution.work_user ? [data.cust_distribution.work_user.id] : [];
        DepartRef.value.appDialog.isChooseDisabled = true;
        DepartRef.value.appDialog.multiple = false;
    } else {
        DepartRef.value.appDialog.multiple = true;
        departTypeObj.itemData = {};
        DepartRef.value.appDialog.chooseArr = type == 'formData' ? formData.employee_ids : [];
    }
    DepartRef.value.departVisble = true;
    DepartRef.value.appDialog.isInit = true;
    DepartRef.value.appDialog.title = '选择员工';
};
// 获取当前选中的员工的数据
const getZWDepartData = (val: any) => {
    creators.value = val;
    formData.employee_ids = [];
    creators.value.forEach((item: any, index: any) => {
        formData.employee_ids[index] = item.id;
    });
    DepartRef.value.departVisble = false;

    // creators.value = val
    // formData.employee_ids = getSetionId('id', val.value)
};

// 前往详情页
const toDetail = (val: any) => {
    if (!val.id) {
        ElMessage.error('当前数据异常，请刷新页面');
        return;
    }
    router.push(`/customer/manage/list/detail?id=${val.id}&type=${val.cust_type}`);
};

onActivated((val: any) => {
    state.searchParams = {
        ...deepCopy(defaultParams),
        ...currentParams.value,
        stage: currentParams.value?.stage || -1
    };
    getListFun();
});
</script>

<style lang="scss" scoped>
:deep .search_picker {
    position: absolute !important ;
    left: -70% !important;
    top: 40 !important;
}
:deep(.zw-search-form) {
    margin: 16px;
}

.container {
    box-sizing: border-box;
    background: #ffffff;
    border: 1px solid #eaeaea;
    overflow: hidden;
}
.customer-manage-list {
    background: white;
    padding: 0 16px;
    .searchForm {
        background: #f9f9f9;
        position: relative;
        .line {
            display: inline-block;
            width: 14px;
            height: 2px;
            background: #969696;
            margin: 0 5px;
            vertical-align: middle;
        }
        .btn-box {
            text-align: right;
            padding: 0px 50px 10px;
        }
    }

    .btns {
        display: flex;
        justify-content: space-between;
        padding-bottom: 16px;
        align-items: center;

        .lable-name {
            font-size: 16px;
        }
    }
    .box-contant {
        // display: grid;
        // grid-template-columns: repeat(auto-fill, minmax(260px, 1fr));
        // gap: 10px;
        display: flex;
        flex-direction: row;
        flex-wrap: nowrap;
        overflow-x: auto;
        overflow-y: hidden;
        .boxs {
            border: 1px solid #eaeaea;
            border-radius: 5px;
            margin-bottom: 20px;
            min-width: 305px;
            margin-right: 20px;
            .title {
                border-bottom: 1px solid #eaeaea;
                padding: 10px 8px;
            }
            .listcontant {
                border: 1px solid #eaeaea;
                margin: 10px 8px;
                .contant {
                    cursor: pointer;
                    .imgsbtn {
                        display: flex;

                        padding: 10px 8px;
                        .titleimg {
                            width: 40px;
                            height: 40px;
                            border: 1px solid #eaeaea;
                            border-radius: 4px;
                        }
                        .image-slot {
                            .el-icon {
                                font-size: 36px;
                            }
                        }
                        .name {
                            color: #33302d;
                            font-size: 14px;
                            margin-left: 10px;
                        }
                        .imgs-ionic {
                            margin-top: 10px;
                            .img-ionic {
                                width: 14px;
                                margin-left: 10px;
                            }
                        }
                    }
                    .enterprise {
                        padding: 10px 8px;
                        display: flex;
                        color: #969696;
                        margin: 2px 0px;
                        font-size: 14px;
                        .enterpriseno {
                            color: #33302d;
                        }
                    }
                    .communicate {
                        justify-content: space-between;
                        border-top: 1px solid #eaeaea;
                    }
                }
            }
        }
    }
}
</style>

<style lang="scss">
.select-box {
    .el-input__inner {
        border: none !important;
        background: #f9f9f9;
    }
}

.table_header_title {
    height: 60px;
    th.el-table__cell {
        background: #f9f9f9;
        padding: 10px 0;
    }
}
</style>
